package com.xhj.bigfactory.bigFactory.Callable;

import java.util.Random;
import java.util.concurrent.*;

/**
 * -
 *
 * @author 周沫 @Date 2021-07-31 @Time 18:47
 */
public class CallableDemo {

  private static class MyThreadRunnable implements Runnable {
    @Override
    public void run() {
      System.out.println(Thread.currentThread().getName() + ": MyThreadRunnable run...");
    }
  }

  private static class MyThreadCallable implements Callable<Integer> {
    @Override
    public Integer call() {
      System.out.println(Thread.currentThread().getName() + ": MyThreadCalable call...");
      int time = new Random().nextInt(1000);
      System.out.println(Thread.currentThread().getName() + ": time = " + time);
      try {
        Thread.sleep(time);
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
      }
      return time;
    }
  }

  public static void main(String[] args)
      throws ExecutionException, InterruptedException, TimeoutException {
    //    MyThreadRunnable myThreadRunnable = new MyThreadRunnable();
    //    myThreadRunnable.run();
    MyThreadCallable myThreadCallable = new MyThreadCallable();
    //    Integer call = myThreadCallable.call();
    //    System.out.println("call=" + call);

    //	  new Thread(myThreadCallable,"AAA").start();

    FutureTask<Integer> futureTask = new FutureTask<>(myThreadCallable);
    //    new Thread(futureTask, "BBB").start();

    try {
      Thread.sleep(20);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
    }
    System.out.println("==================================================================");

    new Thread(
            () -> {
              System.out.println(Thread.currentThread().getName() + ": come in...");
            },
            "QQQ")
        .start();

    Thread f1 = new Thread(futureTask, "f1");
    Thread f2 = new Thread(futureTask, "f2");
    f2.start();
    f1.start();
    Integer integer = futureTask.get(1500, TimeUnit.MILLISECONDS);

    System.out.println("result: " + (integer + 2000));
    System.out.println("asdf");
  }
}
